package com.dragon.modules.yuegou.service.impl.busd;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.busd.GroupEntity;
import com.dragon.modules.yuegou.entity.busd.GroupUserEntity;
import com.dragon.modules.yuegou.entity.system.UserEntity;
import com.dragon.modules.yuegou.entity.system.WxOpenidRefEntity;
import com.dragon.modules.yuegou.enums.code.DistrictCode;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.dragon.modules.yuegou.mapper.busd.GroupUserMapper;
import com.dragon.modules.yuegou.model.busd.Group;
import com.dragon.modules.yuegou.model.busd.GroupUser;
import com.dragon.modules.yuegou.model.system.User;
import com.dragon.modules.yuegou.query.busd.GroupUserQuery;
import com.dragon.modules.yuegou.query.system.UserQuery;
import com.dragon.modules.yuegou.query.system.WxOpenidRefQuery;
import com.dragon.modules.yuegou.service.busd.GroupService;
import com.dragon.modules.yuegou.service.busd.GroupUserService;
import com.dragon.modules.yuegou.service.system.UserService;
import com.dragon.modules.yuegou.service.system.WxOpenidRefService;
import com.dragon.modules.yuegou.web.Check;
import com.google.common.base.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nullable;
import java.util.List;

/**
 * 集团用户 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-19 08:59:40
 * @version 2.0
 */
@Slf4j
@Service("busdGroupUserService")
public class GroupUserServiceImpl
		extends ServiceImpl<GroupUserMapper, GroupUserEntity>
		implements GroupUserService {

	@Autowired
	private UserService userService;

	@Autowired
	private GroupService groupService;

	@Autowired
	private WxOpenidRefService wxOpenidRefService;

	@Override
	public GroupUser login(String username, String password) {
		User user = userService.getGroupUserByUsername(username);
		userService.login(user, password);
		GroupUserEntity gu = getById(user.getId());
		if(gu == null){
			log.info("用户存在，但是用户不是大运营平台的用户，username={}",username);
			throw new DragonException(SystemCode.ACCOUNT_PASSWORD_IS_INCORRECT);
		}else if(gu.getDel()) {
			log.info("用户存在，但是大运营平台用户被删除了，username={}",username);
			throw new DragonException(SystemCode.ACCOUNT_DELETED);
		}
		return new GroupUser(gu);
	}

	@Override
	public GroupUser loginByMobile(String mobile, String password) {
		Check.notNull(mobile, SystemCode.MOBILE_NOTNULL.getMessage());
		log.info("验证账号密码是否正确，开始==，账号={}", mobile);
		Check.notNull(password, SystemCode.PASSWORD_NOTNULL.getMessage());

		UserQuery userQuery = new UserQuery();
		userQuery.setDel(false);
		userQuery.setMobile(mobile);
		List<UserEntity> userList = userService.list(userQuery.toQueryWrapper());
		for (UserEntity user :userList){
			GroupUserEntity entity = getById(user.getId());
			if(entity!=null && !entity.getDel() && validatePwd(new User(user),password)) {
				GroupUser gu = new GroupUser(entity);
				gu.setUser(new User(user));
				return gu;
			}
		}
		throw new DragonException(SystemCode.ACCOUNT_PASSWORD_IS_INCORRECT);
	}

	@Override
	public GroupUser getByMobile(String mobile) {
		Check.notNull(mobile,  SystemCode.MOBILE_NOTNULL.getMessage());
		log.info("验证账号密码是否正确，开始==，账号={}", mobile);

		UserQuery userQuery = new UserQuery();
		userQuery.setDel(false);
		userQuery.setMobile(mobile);
		List<UserEntity> userList = userService.list(userQuery.toQueryWrapper());
		for (UserEntity user :userList){
			GroupUserEntity gu = getById(user.getId());
			if(gu!=null && !gu.getDel()) {
				return new GroupUser(gu);
			}
		}
		throw new DragonException(SystemCode.ACCOUNT_NOT_EXIT);
	}

	private boolean validatePwd(User user, String pwd) {
		String salt = user.getSalt();
		String hash =  DigestUtils.md5Hex(pwd + salt);
		return hash.equals(user.getPassword());
	}
	@Override
	@Transactional
	public String createAdmin(String groupId, String username, String mobile,String nickname, String password) {
		Check.notEmpty(username,SystemCode.ACCOUNT_NOTNULL.getMessage());
		Check.length(username, 0, 20, "账号长度小于20位");
		Check.notEmpty(groupId, SystemCode.GROUP_ID_NOTNULL.getMessage());
		Check.notEmpty(password, SystemCode.PASSWORD_NOTNULL.getMessage());
		
		// 创建用户
		GroupUser groupUser = createCheckGroupUser(groupId, username, mobile, nickname, password);
		String userId = groupUser.getId();

		// 更新集团超级管理员
		Group g = new Group();
		g.setId(groupId);
		g.setAdminId(userId);
		groupService.updateById(g);
		return userId;
	}

	@Override
	public void resetAdminPassword(String groupId, String newPwd) {
		Check.notEmpty(groupId, SystemCode.GROUP_ID_NOTNULL.getMessage());
		Check.notEmpty(newPwd, SystemCode.PASSWORD_NOTNULL.getMessage());
		GroupEntity group = groupService.getById(groupId);
		if(group.getAdminId() == null) {
			throw new IllegalArgumentException("集团尚未设置管理员");
		}
		userService.changePwd(group.getAdminId(), newPwd,null);
	}

	@Override
	@Nullable
	public GroupUser getAdmin(String groupId) {
		Check.notEmpty(groupId, SystemCode.GROUP_ID_NOTNULL.getMessage());
		GroupEntity group = groupService.getById(groupId);
		if(group.getAdminId() == null) {
			return null;
		}
		GroupUserEntity gu = getById(group.getAdminId());
		UserEntity u = userService.getById(group.getAdminId());

		GroupUser groupUser = new GroupUser(gu);
		groupUser.setUser(new User(u));
		return groupUser;
	}

	@Override
	@Transactional
	public GroupUser createAccount(String groupId, String username, @Nullable String mobile, @Nullable String nickname,
			String password) {
		return this.createCheckGroupUser(groupId,username,mobile,nickname,password);
	}

	private GroupUser createCheckGroupUser(String groupId, String username, String mobile, String nickname,String password){
		Check.notNull(username, SystemCode.ACCOUNT_NOTNULL.getMessage());
		Check.length(username, 0, 20, "账号长度小于20位");
		Check.notEmpty(groupId, SystemCode.GROUP_ID_NOTNULL.getMessage());
		Check.notEmpty(password, SystemCode.PASSWORD_NOTNULL.getMessage());

		//查询集团用户数量
		GroupUserQuery query = new GroupUserQuery();
		query.setGroupId(groupId);
		query.setDel(false);
		Long userCount = count(query.toQueryWrapper());

		//查询集团信息
		GroupEntity group = groupService.getById(groupId);

		// 判断添加用户不能超过商圈设置可添加用户上限
		if (userCount >= group.getUserQuantity()) {
			throw new DragonException(SystemCode.USER_GROUP_SX);
		}
		return createGroupUser(groupId,username, mobile, nickname, password);
	}

	private GroupUser createGroupUser(String groupId, String username, String mobile, String nickname,
			String password) {
		User sysUser = userService.getGroupUserByUsername(username);
		if (sysUser != null) {
			throw new DragonException(SystemCode.ACCOUNT_EXISTS);
		}
		sysUser = userService.getGroupUserByMobile(mobile);
		if (sysUser != null) {
			throw new DragonException(SystemCode.MOBILE_EXISTS);
		}
		sysUser = userService.createAccount(username, mobile, nickname, password);
		GroupUser groupUser = new GroupUser();
		groupUser.setId(sysUser.getId());
		groupUser.setUserId(sysUser.getId());
		groupUser.setGroupId(groupId);
		baseMapper.insert(groupUser);
		groupUser.setUser(sysUser);
		return groupUser;
	}

	@Override
	@Transactional
	public void deleteAccount(String groupId, String userId) {
		preRemoveUser(groupId, userId);
		// 删除系统用户
		userService.deleteAccount(userId);
		// 删除集团用户
		removeById(userId);
	}

	@Override
	public void enableUser(String groupId, String userId) {
		userService.enableUser(userId);
	}

	@Override
	public void disableUser(String groupId, String userId) {
		preRemoveUser(groupId, userId);
		userService.disableUser(userId);
	}

	@Override
	public GroupUser getUserByWxOpenId(String openId, String appid) {
		if (StringUtils.isBlank(openId)){
			return null;
		}
		//判断会员是否存在
		WxOpenidRefQuery query = new WxOpenidRefQuery();
		query.setWxOpenId(openId);
		query.setAppid(appid);
		List<WxOpenidRefEntity> wxOpenidRefEntityList = wxOpenidRefService.list(query.toQueryWrapper());
		if (!CollectionUtils.isEmpty(wxOpenidRefEntityList)){
			WxOpenidRefEntity wxOpenidRef = wxOpenidRefEntityList.get(0);
			String userId = wxOpenidRef.getUserId();

			GroupUserEntity gu = getById(userId);
			UserEntity u = userService.getById(userId);

			GroupUser groupUser = new GroupUser(gu);
			groupUser.setUser(new User(u));
			return groupUser;
		}
		return new GroupUser();
	}

	/**
	 * 删除或禁用集团用户的前置条件
	 * @param groupId
	 * @param userId
	 */
	private void preRemoveUser(String groupId, String userId) {
		Check.notEmpty(groupId, SystemCode.GROUP_ID_NOTNULL.getMessage());
		Check.notEmpty(userId, "必须提供用户ID");
		GroupEntity group = groupService.getById(groupId);
		
		// 防止误操作
		// 不能删除大运营平台给的管理员账号
		if(Objects.equal(group.getAdminId(), userId)) {
			throw new DragonException(DistrictCode.CANNOT_DELETE_ADMIN);
		}

	}

}